/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.editor.history;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.gidoo.cms.data.Folder;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.gidoo.cms.data.Page;
import org.gidoo.cms.editor.EditorPage;
import org.gidoo.wickettools.MessageBox;
import org.gidoo.wickettools.XHTMLDiff;

/**
 *
 * @author thomas
 */
public class HistoryPanel extends Panel
{
  EditorPage parentPage;
  Folder theFolder;
  
  ListView lsvRevisions;
  List<Page> history;
  
  public HistoryPanel(String id, Folder folder, EditorPage parent)
  {
    super(id);
    this.theFolder = folder;
    this.parentPage = parent;
    
    Form formMain = new Form("formMain");
    
    history = new ArrayList<Page>();
    if(theFolder != null && theFolder.getHistory() != null)
    {
      history.addAll(theFolder.getHistory());
    }
    
    lsvRevisions = new ListView("lsvRevisions", history) {

      @Override
      protected void populateItem(ListItem item)
      {
        final Page rev = history.get(item.getIndex());
        final Page prev = item.getIndex() > 0 ? 
          history.get(item.getIndex()-1) : null;
        
        Link lnkDiffPrev =new Link("lnkDiffPrev") {
          @Override
          public void onClick()
          {
            diffToPrevious(prev, rev);
          }
        };
        lnkDiffPrev.setVisible(item.getIndex() > 0);
        item.add(lnkDiffPrev);
        
        item.add(new Link("lnkDiffCur") {
          @Override
          public void onClick()
          {
            diffToCurrent(rev);
          }
        });
        DateFormat d =DateFormat.getDateTimeInstance();
        String ds = getString("unknown");
        if(rev.getCreatedTime() != null)
        {
          ds = d.format(rev.getCreatedTime());
        }
        item.add(new Label("lblDate", new Model(ds)));
        
        item.add(new Label("lblAuthor", new Model(rev.getCreatedBy().getLoginName())));
        
        item.add(new AjaxLink("lnkRestore") {

          @Override
          public void onClick(AjaxRequestTarget target)
          {
            restore(rev);
            info(getString("waitingforpublisher"));
            target.addComponent(parentPage.getFeedbackPanel());
          }
        });
      }
    };
    formMain.add(lsvRevisions);
    
    add(formMain);
    if(theFolder == null)
    {
      formMain.setVisible(false);
    }
  }
  
  private void restore(Page oldRev)
  {
    if(theFolder.getPageWaitingForPublisher() != null)
    {
      theFolder.getHistory().add(theFolder.getPageWaitingForPublisher());
    }
    theFolder.setPageWaitingForPublisher(oldRev);
  }
  
  private void diffToCurrent(Page old)
  {
    if(theFolder == null || theFolder.getPublishedPage() == null)
    {
      error(getString("error"));
      return;
    }
    String diff = XHTMLDiff.doDiff(
      theFolder.getPublishedPage().getContentAsXML(),
      old.getContentAsXML());
    
    String msg = 
      "<p>" + getString("oldtitle") + old.getTitle() + "<br />" +
      getString("newtitle") + theFolder.getPublishedPage().getTitle() + "</p>" +
      "<table style=\"width:100%; text-align:left;\" >" +
      "<tr>" +
      "<th>" + getString("current") + "</th>" +
      "<th>" + getString("old") + "</th>" +
      "</tr>" + diff +      
      "</table>";
    
    MessageBox msgBox = new MessageBox(
      getString("diffoldcurrent"),
      msg, true,
      MessageBox.MessageBoxButtons.OK,
      parentPage, null
    );
    
    setResponsePage(msgBox);
  }
 
  private void diffToPrevious(Page revNewer, Page revOlder)
  {
    if(theFolder == null || theFolder.getPublishedPage() == null
      || revNewer == null || revOlder == null)
    {
      error(getString("error"));
      return;
    }
    String diff = XHTMLDiff.doDiff(
      revOlder.getContentAsXML(),
      revNewer.getContentAsXML());
    
    String msg = 
      "<p>" + getString("oldtitle") + revOlder.getTitle() + "<br />" +
      getString("newtitle") + revNewer.getTitle() + "</p>" +
      "<table style=\"width:100%; text-align:left;\";>" +
      "<tr>" +
      "<th>" + getString("older") + "</th>" +
      "<th>" + getString("newer") + "</th>" +
      "</tr>" + diff +      
      "</table>";
    
    MessageBox msgBox = new MessageBox(
      getString("diffoldcurrent"),
      msg, true,
      MessageBox.MessageBoxButtons.OK,
      parentPage, null
    );
    
    setResponsePage(msgBox);
  }
  
  public void updateDataAndView( Folder folder, EditorPage parent)
  {
    if(parent == null)
      throw(new NullPointerException());
    
    this.theFolder = folder;
    this.parentPage = parent;
    
    history = new ArrayList<Page>();
    if(theFolder != null && theFolder.getHistory() != null)
    {
      history.addAll(theFolder.getHistory());
    }
    
    lsvRevisions.setList(history);
  }
  
}
